package com.ytd.common.util;


import android.text.TextUtils;

import com.ytd.common.bean.RequestInfo;

import java.util.Random;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AESUtils {
    public static String encrypt128(String sSrc, String sKey) {
        if (sKey == null) {
            return "";
        }
        // 判断Key是否为16位
        if (sKey.length() != 16) {
            return "";
        }
        byte[] raw = new byte[0];
        try {
            raw = sKey.getBytes("utf-8");

            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");//"算法/模式/补码方式"
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));

            return WTBase64.encode(encrypted);//此处使用BASE64做转码功能，同时能起到2次加密的作用。
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    // 解密
    public static String decrypt128(String sSrc, String sKey) {
        try {
            // 判断Key是否正确
            if (sKey == null) {
                return "";
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
                return "";
            }
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = WTBase64.decode(sSrc);
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original, "utf-8");

                return originalString;
            } catch (Exception e) {
                e.printStackTrace();
                return "";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return "";
        }
    }

    public static String upJson(String json, String AESKey) {
        if (!TextUtils.isEmpty(json) && json.contains("heartBeat")) {
            LogUtil.d("send:heartBeat");
        } else {
            LogUtil.d("send:" + json);
        }
        RequestInfo info = new RequestInfo();
        info.secretKey = YtdConfig.getSecretKey();
        info.key = RSAUtils.encryptByPublicKey(AESKey.getBytes(), WTBase64.decode(YtdConfig.getRsaPublicKey()));
        info.body = encrypt128(json, AESKey);
        return GsonUtil.toJson(info);
    }

    private static final String ALLOWED_CHARACTERS = "0123456789qwertyuiopasdfghjklzxcvbnm";

    public static String AESKey() {

        final Random random = new Random();

        final StringBuilder sb = new StringBuilder(16);

        for (int i = 0; i < 16; i++) {
            sb.append(ALLOWED_CHARACTERS.charAt(random.nextInt(ALLOWED_CHARACTERS.length())));
        }
        return sb.toString();

    }
}
